<template>
  <div class="user-management-container">
    <div class="page-header">
      <span class="page-title">用户管理</span>
      <el-button type="primary" @click="beforeAddUser" class="add-user-btn">新建用户</el-button>
    </div>

    <el-dialog
        :title="dialogTitle"
        class="user-dialog"
        v-model="dialogVisible"
        :before-close="handleClose">
      <el-form label-width="80px" label-position="top" class="dialog-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input placeholder="请输入用户名" v-model="saveUserForm.username" :disabled="saveUserForm.userId != null && saveUserForm.userId != ''"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账号">
              <el-input placeholder="请输入账号" v-model="saveUserForm.account"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="密码">
              <el-input placeholder="请输入密码" v-model="saveUserForm.password"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称">
              <el-input placeholder="请输入昵称" v-model="saveUserForm.nickname"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年龄">
              <el-input placeholder="请输入年龄" v-model="saveUserForm.age"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="积分">
              <el-input placeholder="0" v-model="saveUserForm.points" :disabled="saveUserForm.userId == null || saveUserForm.userId == ''"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱">
              <el-input placeholder="请输入邮箱" v-model="saveUserForm.email"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话">
              <el-input placeholder="请输入电话" v-model="saveUserForm.phone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="地址">
              <el-input placeholder="请输入地址" v-model="saveUserForm.address"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="身份">
              <el-select placeholder="请选择" v-model="saveUserForm.type">
                <el-option label="居民" value="RESIDENT"></el-option>
                <el-option label="管理员" value="ADMIN"></el-option>
                <el-option label="员工" value="STAFF"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </template>
    </el-dialog>

    <!-- 用户搜索卡片 -->
    <el-card class="search-card">
      <el-form :inline="true" class="search-form">
        <el-form-item label="用户搜索">
          <el-input placeholder="请输入用户名" v-model="searchUserForm.username" @keydown.enter="loadUser"></el-input>
        </el-form-item>
        <el-form-item label="昵称搜索">
          <el-input placeholder="请输入昵称" v-model="searchUserForm.nickname" @keydown.enter="loadUser"></el-input>
        </el-form-item>
        <el-form-item label="用户身份" style="width: 180px;">
          <el-select placeholder="请选择" v-model="searchUserForm.type" @change="loadUser">
            <el-option label="管理员" value="ADMIN"></el-option>
            <el-option label="居民" value="RESIDENT"></el-option>
            <el-option label="员工" value="STAFF"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="form-buttons">
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="loadUser">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表卡片 用户表格数据-->
    <el-card class="table-card">
      <el-table :data="userArr" class="user-table">
        <el-table-column label="编号" type="index" width="80" align="center"/>
        <el-table-column label="用户名" prop="username" align="center" />
        <el-table-column label="账号" prop="account" align="center" />
        <el-table-column label="昵称" prop="nickname" align="center" />
        <el-table-column label="年龄" prop="age" align="center" />
        <el-table-column label="积分" prop="points" align="center" />
        <el-table-column label="邮箱" prop="email" align="center" />
        <el-table-column label="电话" prop="phone" align="center" />
        <el-table-column label="地址" prop="address" align="center" />
        <el-table-column label="身份" prop="type" align="center" :formatter="userTypeFormatter" />
        <el-table-column label="操作" align="center" width="120">
          <template #default="scope">
            <div class="action-buttons">
              <el-button link type="primary" @click="editUser(scope.row.userId)">编辑</el-button>
              <el-button link type="danger" @click="deleteUser(scope.row.userId,scope.row.username)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <el-empty v-if="userArr.length === 0 && !loading" description="暂无数据" />
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchUserForm.pageNum"
          :page-sizes="[5, 10, 15]"
          :page-size="searchUserForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalPage"
      />
    </el-card>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import axios from "axios";

//定义变量控制弹窗是否出现
const dialogVisible = ref(false);

const totalPage = ref(0);

//定义对象用来保存表单中的员工数据
const saveUserForm = ref({
  userId: '',
  username: '',
  account: '',
  nickname: '',
  age: '',
  points: '',
  email: '',
  phone: '',
  address: '',
  type: '',
  createAt: '',
  updatedAt: '',
});

//定义保存用户的方法
const saveUser = () => {
  if (!saveUserForm.value.userId) {
    axios.post(BASE_URL + '/api/users/add', saveUserForm.value)
        .then((response) => {
          console.log(response.data);
          if (response.data.state === 2001) {
            ElMessage.success('保存成功！');
            dialogVisible.value = false;
            saveUserForm.value = {};
            loadUser();
          } else {
            ElMessage.error(response.data.msg);
          }
        })
  } else {
    axios.put(BASE_URL + '/api/users/update', saveUserForm.value)
        .then((response) => {
          if (response.data.state === 2001) {
            ElMessage.success('修改成功！');
            dialogVisible.value = false;
            saveUserForm.value = {};
            loadUser();
          } else {
            ElMessage.error(response.data.msg);
          }
        })
  }
}

//处理弹窗关闭的方法
const handleClose = () => {
  dialogVisible.value = false;
  saveUserForm.value = {};
}

//定义对象来保存用户查询的条件
const searchUserForm = ref({
  username: '',
  nickname: '',
  type: '',
  pageNum: 1,
  pageSize: 5
});

//定义对象保存查询到的用户表格数据
const userArr = ref([]);

//定义加载用户列表的方法
const loadUser = () => {
  axios.get(BASE_URL + '/api/users/select', {params: searchUserForm.value})
      .then((response) => {
        if (response.data.state === 2001) {
          userArr.value = response.data.data.list;
          totalPage.value = response.data.data.totalPage;
          console.log(userArr.value);
        } else {
          ElMessage.error(response.data.message);
        }
      })
}


//页面一加载完毕,立即执行
onMounted(() => {
  loadUser();
})

//重置搜索
const resetSearch = () => {
  searchUserForm.value = {
    username: '',
    nickname: '',
    type: '',
    pageNum: 1,
    pageSize: 5
  };
  loadUser();
}

//定义点击"新建用户"按钮时调用的方法
const beforeAddUser = () => {
  dialogTitle.value = '新建用户';
  dialogVisible.value = true;
}

//定义变量用来保存弹窗的标题
const dialogTitle = ref('新建用户');

//定义编辑用户的方法
const editUser = (userId) => {
  dialogVisible.value = true;
  dialogTitle.value = '编辑用户';
  axios.get(BASE_URL + `/api/users/select?userId=${userId}`)
      .then((response) => {
        if (response.data.state === 2001) {
          saveUserForm.value = response.data.data.list[0];
        } else {
          ElMessage.error(response.data.msg);
        }
      })
}

//创建删除员工的方法
const deleteUser = (userId, username) => {
  if (confirm('您确认要删除 [' + username + '] 吗？')) {
    axios.delete(BASE_URL + `/api/users/delete/id/${userId}`)
        .then((response => {
          if (response.data.state === 2001) {
            ElMessage.success('删除成功');
            loadUser();
          } else {
            ElMessage.error(response.data.msg);
          }
        }))
  }
}

const handleSizeChange = (pageSize) => {
  searchUserForm.value.pageSize = pageSize;
  loadUser();
}

const handleCurrentChange = (pageNum) => {
  searchUserForm.value.pageNum = pageNum;
  loadUser();
}

const userTypeFormatter = (row, column, cellValue, index) => {
  if (!userArr.value) {
    return cellValue;
  }
  if (cellValue == 'RESIDENT') {
    cellValue = '居民';
  } else if (cellValue == 'ADMIN') {
    cellValue = '管理员';
  } else if (cellValue == 'STAFF') {
    cellValue = '员工';
  }
  return cellValue;
}
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}

.add-user-btn {
  padding: 10px 20px;
  font-weight: 500;
}

.user-dialog {
  border-radius: 12px;
}

.dialog-form {
  padding: 10px 0;
}

.dialog-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.dialog-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 16px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
}

.search-form :deep(.el-form-item__label) {
  font-weight: 500;
  margin-right: 8px;
}

.form-buttons {
  margin-left: auto;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.user-table {
  width: 100%;
}

.user-table :deep(th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.user-table :deep(.el-table__row) {
  height: 60px;
}

.user-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

:deep(.el-button) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-table .cell) {
  padding: 0 10px;
}
</style>